package com.example.handler.exception;

import com.example.domain.ResponseResult;
import com.example.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SystemException.class)
    public ResponseResult systemExceptionHandler(SystemException e){
        log.error("出现了异常"+e);
        return ResponseResult.errorResult(e.getCode(),e.getMsg());
    }

//    @ExceptionHandler(Exception.class)
//    public ResponseResult exceptionHandler(Exception e){
//
//        log.error("出现了异常"+e);
//        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),e.getMessage());
//    }
//    @ExceptionHandler(InsufficientAuthenticationException.class)
//    public ResponseResult nullExceptionHandler(Exception e){
//
//        log.error("出现了异常"+e);
//        return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_ERROR);
//    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult methodNullExceptionHandler(MethodArgumentNotValidException e){
        log.error("出现了异常"+e);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),message);
    }
}
